//
//  AuthViewController.m
//  Weibo
//
//  Created by wpapple on 16/6/1.
//  Copyright © 2016年 wpapple. All rights reserved.
//

#import "AuthViewController.h"
#import "TabBarController.h"
#import "HomeViewController.h"

@interface AuthViewController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *webView;

@end

// https://api.weibo.com/oauth2/authorize?client_id=1149386290&redirect_uri=http://www.baidu.com

@implementation AuthViewController

-(void)loadView
{
    UIWebView *webView = [[UIWebView alloc]init];
    
    webView.frame = [UIScreen mainScreen].bounds;
    
    self.webView = webView;
    self.view = webView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close:)];
    
    NSString *authStr = @"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@";
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:authStr,WPAppKey,WPRedirectURI]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    self.webView.delegate = self;
    
    [self.webView loadRequest:request];
}

-(void)close:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    
    if ([url containsString:@"code"]) {
        NSRange range = [url rangeOfString:@"code"];
        
        NSString *code = [url substringFromIndex:range.location + range.length +1];
        
        [self loadRequestAccesstoken:code];
        
        return NO;
    }
    
    return YES;

}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    
}

#pragma mark - access token 请求
-(void)loadRequestAccesstoken:(NSString *)code
{
    NSString *authStr = @"https://api.weibo.com/oauth2/access_token";
    
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:authStr,WPAppKey,WPRedirectURI]];
    
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"client_id"] = WPAppKey;
     parameters[@"client_secret"] = WPAppSecret;
     parameters[@"grant_type"] = @"authorization_code";
    
    parameters[@"code"] = code;
    parameters[@"redirect_uri"] = WPRedirectURI;
    
    
    [manager POST:authStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
         NSLog(@"请求成功");
        
        //保存帐号信息
        WPAccount *account = [[WPAccount alloc]init];
        
        account.uid = responseObject[@"uid"];
        account.access_token = responseObject[@"access_token"];
        
        [account save];
        
        //跳转到首页

        UIStoryboard *story = [UIStoryboard storyboardWithName:@"main" bundle:nil];
        
        UIViewController *vc = [story instantiateInitialViewController];
        
        [UIApplication sharedApplication].keyWindow.rootViewController = vc;
        
    
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败");
    }];

}

@end
